/*
 * Copyright (C) 2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package top.xbaistack.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.xbaistack.common.Result;

/**
 * 全局响应主体过渡包装增强类，返回值将统一被包装成{@link Result}对象， 而不管是否存在实际的返回值（即便它是{@code void}）。
 *
 * @author xbaistack
 * @since 2025/03/25
 * @see Result
 */
@ControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class GlobalResponseBody implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter mp, Class<? extends HttpMessageConverter<?>> converterType) {
        return mp.hasMethodAnnotation(RequestMapping.class);
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter mp,
            MediaType contentType,
            Class<? extends HttpMessageConverter<?>> converterType,
            ServerHttpRequest request,
            ServerHttpResponse response
    ) {
        if (body == null) {
            return Result.ok();
        }
        return body instanceof Result ? body : Result.ok(body);
    }

}
